#include <stdio.h>
#include "types.h"
#include "cpu.h"
#include "memory.h"

void op_0x5a()
{
    g_reg_a = 0;
}

void op_0x5b()
{
    BYTE operand;
    if (mem_get(g_pc + 1, &operand) == R_SUCCESS)
    {
        g_reg_a = operand;
    }
}

void op_0x5c()
{
    BYTE operand;
    if (mem_get(g_pc + 1, &operand) == R_SUCCESS)
    {
        g_reg_a += operand;
    }
}

void op_0x5d()
{
    BYTE address;
    if (mem_get(g_pc + 1, &address) == R_SUCCESS)
    {
        mem_set(address, g_reg_a);
    }
}

void op_0x5e()
{
    BYTE hi, lo;
    if (mem_get(0xff, &hi) == R_SUCCESS && mem_get(0xfe, &lo) == R_SUCCESS)
    {
        int val = (hi << 8 | lo);
        printf("%d (hex: %x)", val, val);
    }
}

static void cpu_tick(BYTE opcode)
{
    INSTRUCTION inst;
    for (int i = 0; i < sizeof(g_instructions); i++)
    {
        inst = g_instructions[i];
        if (inst.opcode == opcode)
            break;
    }

    inst.callback();

    g_pc += inst.len;
}

void cpu_reset()
{
    g_pc = 0;
}

void cpu_cycle()
{
    while(1)
    {
        BYTE opcode;
        if (g_pc > 0xef)
            break;
        if (mem_get(g_pc, &opcode) != R_SUCCESS)
            break;
        if (opcode == 0)
            break;
        cpu_tick(opcode);
    }
}
